﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Runtime.Caching;
using Newtonsoft.Json.Linq;

namespace XXF.BasicService.ConfigCenter.Cached
{
    public class CachedHandle
    {

        private static System.Runtime.Caching.MemoryCache cache = System.Runtime.Caching.MemoryCache.Default;//缓存

        public static ConfigsModel mother;//保存的模板

        private static string name = "ConfigCenter";//缓存名称

        static CachedHandle()
        {
            ConfigsModel son = cache.Get(name) as ConfigsModel;
            if (son == null)
            {
                son = new ConfigsModel();
                cache.Add(name, son, new DateTimeOffset(DateTime.Now.AddDays(5)));
            }
            mother = son.Clone();
        }

        public static void SetConfigCache()
        {
            if (mother == null)
                mother = new ConfigsModel();
            if (cache.Get(name) != null)
                cache.Remove(name);
            cache.Add(name, mother, new DateTimeOffset(DateTime.Now.AddDays(5)));
        }

        public static void UpOrAddCache(ConfigsModel configmodel)
        {
            if (mother == null)
            {
                mother = new ConfigsModel();

            }
            List<Config> configs = configmodel.Configs as List<Config>;
            mother.Update = configmodel.Update;
            foreach (var item in configs)
            {
                Config config = mother.Configs.FirstOrDefault(o => o.csmc == item.csmc && o.xmdh == item.xmdh);
                if (config != null)
                {
                    config.csz = item.csz;
                }
                else
                {
                    mother.Configs.Add(item);
                }
            }
            SetConfigCache();
        }

        public static List<Config> GetConfigCacheList(string xmdh)
        {
            List<Config> configs=new List<Config>();
            configs = mother.Configs.Where(o => o.xmdh == xmdh).ToList();
            if (configs.Count == 0)
                return null;
            else
                return configs;
        }

        public static string GetConfigCache(string csmc, string xmdh)
        {
            Config config = mother.Configs.FirstOrDefault(o => o.csmc == csmc && o.xmdh == xmdh);
            if (config == null)
            {
                return null;
            }
            else
            {
                return config.csz;
            }
        }
    }
}
